package flc.ast.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;

import VideoHandle.EpAudio;
import VideoHandle.EpEditor;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityAudioCutBinding;
import flc.ast.utils.Content;
import flc.ast.view.BaseAvTrackView;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;

public class AudioCutActivity extends BaseAc<ActivityAudioCutBinding> implements IAudioPlayer.IListener {

    public static String audioPath;
    protected IAudioPlayer mAudioPlayer;
    private boolean isInitTrackViewDuration = false;
    private long mStartTime = 0;
    private long mEndTime = 0;
    private long mTotalTime = 0;

    @Override
    protected int onCreate() {
        return R.layout.activity_audio_cut;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivAudioCutBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.tvAudioCutSave.setOnClickListener(this);

        mAudioPlayer = createAudioPlayer();
        mAudioPlayer.play(audioPath);
        mAudioPlayer.setListener(this);

        mDataBinding.trackView.setListener(new BaseAvTrackView.IListener() {
            @Override
            public void onStartTimeChanged(long startTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) startTime);
                    mAudioPlayer.resume();
                }
                mStartTime = startTime;
            }

            @Override
            public void onEndTimeChanged(long endTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) endTime);
                    mAudioPlayer.resume();
                }
                mEndTime = endTime;
            }

            @Override
            public void onStartEndTimeChanged(long startTime, long endTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) startTime);
                    mAudioPlayer.resume();
                }
                mStartTime = startTime;
                mEndTime = endTime;
            }
        });

    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.ivPlay) {//播放
            if (mAudioPlayer == null) {
                return;
            }
            if (mAudioPlayer.isPlaying()) {
                mAudioPlayer.pause();
            } else {
                mAudioPlayer.resume();
            }
        } else if (id == R.id.tvAudioCutSave) {//保存
            save();
        }
    }

    @Override
    protected void initData() {

    }

    private void save() {
        String path = FileUtil.generateFilePath(Content.myTemp, ".mp3");
        showDialog(getString(R.string.audio_cut_ing));
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                EpAudio epAudio = new EpAudio(audioPath);
                float startTime = mDataBinding.trackView.getStartTime() / 1000f;
                float duration = mDataBinding.trackView.getEndTime() / 1000f - startTime;
                if (duration < 0) {
                    duration = 0;
                }
                epAudio.clip(startTime, duration);
                EpEditor.audioExec(epAudio, path, new OnEditorListener() {
                    @Override
                    public void onSuccess() {
                        emitter.onNext(true);
                    }

                    @Override
                    public void onFailure() {
                        emitter.onNext(false);
                    }

                    @Override
                    public void onProgress(float progress) {

                    }
                });
            }

            @Override
            public void accept(Boolean result) {
                dismissDialog();
                if (result) {
                    ToastUtils.showShort(getString(R.string.audio_cut_suc));
                    FileP2pUtil.copyPrivateAudioToPublic(mContext, audioPath);
                    startActivity(HomeActivity.class);
                }
            }
        });
    }

    /**
     * 子类可覆盖重写，创建对应的播放器
     *
     * @return
     */
    @NonNull
    protected IAudioPlayer createAudioPlayer() {
        return new AudioPlayerImpl();
    }

    @Override
    public void onUpdatePlayTime(int curPlayTime, int duration) {
        if (!isInitTrackViewDuration) {
            isInitTrackViewDuration = true;
            mEndTime = duration;
            mDataBinding.trackView.setDuration(duration);
            mDataBinding.tvPlayRight.setText(TimeUtils.millis2String(duration, "mm:ss"));
            mTotalTime = duration;
        }
        mDataBinding.trackView.setPlayTime(curPlayTime);
        mDataBinding.sbPlay.setMax((int) duration / 1000);
        mDataBinding.sbPlay.setProgress(curPlayTime / 1000);
    }

    @Override
    public void onPlayChange(boolean isPlaying) {
        if (isPlaying) {
            mDataBinding.ivPlay.setImageResource(R.drawable.aypbf);
        } else {
            mDataBinding.ivPlay.setImageResource(R.drawable.aypzt);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAudioPlayer != null) {
            mAudioPlayer.resume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAudioPlayer != null) {
            mAudioPlayer.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAudioPlayer != null) {
            mAudioPlayer.stop();
        }
        FileUtils.deleteAllInDir(PathUtils.getFilesPathExternalFirst() + Content.myTemp);
    }

}